package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.ClassInfo;
import com.ruoyi.business.domain.bo.ClassInfoBo;
import com.ruoyi.business.domain.vo.ClassInfoVo;
import com.ruoyi.business.domain.vo.UserVo;
import com.ruoyi.business.mapper.ClassInfoMapper;
import com.ruoyi.business.mapper.UserMapper;
import com.ruoyi.business.service.IClassInfoService;
import com.ruoyi.common.core.domain.model.InternalObjectPage;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysTableObjService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 最爱喝兽奶
 * @create 2022/9/2
 **/
@SuppressWarnings("ALL")
@Service
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo> implements IClassInfoService {

    @Autowired
    private ISysTableObjService sysTableObjService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public TableDataInfo<ClassInfoVo> queryClassListByPage(ClassInfoBo bo) {
        if (SecurityUtils.isAdmin(bo.getTeacherId())) {
            bo.setTeacherId(null);
        }
        Page<ClassInfoVo> page = baseMapper.queryClassListByPage(PageUtils.buildPage(bo), bo);
        return PageUtils.buildTableDataInfo(page);
    }

    @Override
    public InternalObjectPage selectRefTableByName(String refColumn, Integer pageSize, Integer currentPage, String filterContent, String filterId) {
        InternalObjectPage pageDomain = new InternalObjectPage();
        //主键Map
        Map<String, String[]> pkMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        //标题头
        Map<String, Map<String, String>> titleMap = new LinkedHashMap();
        String sql = null;
        Page pageList = new Page();
        Page page = new Page();
        //是否开启分页，不开启默认查询前10000条记录（前端已限制默认分页数量，此处为保障内部对象的正常使用）
        if (currentPage == null || pageSize == null) {
            page = new Page(1, 10000);
        } else {
            page = new Page(currentPage, pageSize);
        }
        String[] refColumns = {"classId"};
        if (StringUtils.equalsAnyIgnoreCase(refColumn, refColumns)) {

            Map<String, String> classMap = new LinkedHashMap();
            classMap.put("showColumn", "班级");
            titleMap.put("classId", classMap);
            pkMap.put("classId", new String[]{"id", "class_name"});
            map.put("classId", "SELECT id as \"refColumn\",class_name as \"showColumn\"   FROM T_CLASS_INFO");

            sql = map.get(refColumn);
            //筛选
            if (StringUtils.isNotEmpty(filterContent)) {
                if (StringUtils.isNotEmpty(pkMap.get(refColumn)[1])) {
                    sql = sql + " where  " + pkMap.get(refColumn)[1] + " like " + "'%" + filterContent + "%'";
                }
            }
            //回显与判断
            if (StringUtils.isNotEmpty(filterId)) {
                List<String> list = Arrays.asList(filterId.split(","));
                String ids = list.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
                if (StringUtils.isNotEmpty(pkMap.get(refColumn))) {
                    sql = sql + " where " + pkMap.get(refColumn)[0] + " in " + "(" + ids + ")";
                }
            }
        }
        try {
            pageList = sysTableObjService.executeSelectSqlSelectRefTableByName(page, sql);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException().setMessage("内部对象字段配置信息错误");
        }
        List<Map<String, String>> records = (List<Map<String, String>>) pageList.getRecords().stream().map(item -> {
            if (item instanceof Map) {
                Map m = (Map) item;
                if (m.containsKey("refColumn")) {
                    Object value = m.get("refColumn");
                    if (value instanceof BigInteger) {
                        m.put("refColumn", String.valueOf(value));
                    } else if (value instanceof Long) {
                        m.put("refColumn", String.valueOf(value));
                    }
                }
            }
            return item;
        }).collect(Collectors.toList());
        pageDomain.setTotal(page.getTotal());
        pageDomain.setTitle(titleMap.get(refColumn));
        pageDomain.setDataList(records);
        return pageDomain;
    }

    public void checkClassId(ClassInfoBo bo) {
        // 查询课程id是否重名
        List<ClassInfo> classInfos = baseMapper.selectList(new QueryWrapper<ClassInfo>().eq("class_id", bo.getClassId()));
        if (classInfos != null && classInfos.size() != 0) {
            throw new RuntimeException("课程id不可重名");
        }
    }

    @Override
    public void insertClassInfo(ClassInfoBo bo) {
        ClassInfo classInfo = new ClassInfo();
        BeanUtils.copyProperties(bo, classInfo);
        // 检查课程id是否重名
        checkClassId(bo);
        classInfo.setAssignTeachers("," + bo.getAssignTeachers().trim() + ",");
        baseMapper.insert(classInfo);
    }

    @Override
    public ClassInfoVo getClassInfo(String id) {
        ClassInfo classInfo = baseMapper.selectById(id);
        ClassInfoVo vo = new ClassInfoVo();
        BeanUtils.copyProperties(classInfo, vo);
        return vo;
    }

    @Override
    public void updateClassInfo(ClassInfoBo bo) {
        ClassInfo classInfo = new ClassInfo();
        BeanUtils.copyProperties(bo, classInfo);
        // 检查课程id是否重名
//        checkClassId(bo);
        baseMapper.updateById(classInfo);
    }

    @Override
    public void deleteClassInfo(String id) {
        baseMapper.deleteById(id);
    }

    @Override
    public List<UserVo> queryMemberByClassId(String id) {
        List<UserVo> vos = userMapper.selectUserByClass(new String[]{id});

        return vos;
    }
}
